package com.transcendence.mobileguard.activity;

import android.content.DialogInterface;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.res.AssetManager;
import android.os.Bundle;
import android.os.Environment;
import android.view.animation.AlphaAnimation;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AlertDialog;

import com.google.gson.Gson;
import com.transcendence.mobileguard.db.AddressQuery;
import com.transcendence.mobileguard.entity.AppInfo;
import com.transcendence.mobileguard.global.Config;
import com.transcendence.mobileguard.R;
import com.transcendence.mobileguard.net.HttpRequest;
import com.transcendence.mobileguard.net.RequestCallback;
import com.transcendence.mobileguard.utils.log.LogUtils;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

/**
 * @author joephone
 * @date 2024/12/27
 * @desc 闪屏页
 * @edition 1.0
 */

public class SplashActivity extends BaseActivity {

    private TextView mTvVersion;
    private AppInfo mLocalAppInfo;
    private AppInfo mRemoteAppInfo;
    private TextView mTvProgress;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_splash);
    }

    @Override
    public void initVariables() {
        mLocalAppInfo = getLocalAppInfo();
        LogUtils.d(mLocalAppInfo.toJson());
    }

    @Override
    protected void initViews(Bundle savedInstanceState) {
        setContentView(R.layout.activity_splash);

        mTvVersion = (TextView) findViewById(R.id.tv_version);
        mTvVersion.setText("版本号："+mLocalAppInfo.getVersionName());

        mTvProgress = (TextView) findViewById(R.id.tv_progress);

        RelativeLayout rlRoot = (RelativeLayout) findViewById(R.id.rl_root);
        AlphaAnimation anim = new AlphaAnimation(0.3f, 1);
        anim.setDuration(1000);
        rlRoot.startAnimation(anim);
    }

    /** 获取当前App版本信息 */
    private AppInfo getLocalAppInfo() {
        AppInfo appInfo = new AppInfo();
        try {
            PackageManager packageManager = getPackageManager();
            PackageInfo packageInfo = packageManager.getPackageInfo(getPackageName(), 0);
            appInfo.setVersionCode(packageInfo.versionCode);
            appInfo.setVersionName(packageInfo.versionName);
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return appInfo;
    }


    @Override
    protected void loadData() {
        getAppInfoFromServer();
        copyDb(AddressQuery.DB_NAME);
    }

    /** 从服务器中获取版本信息 */
    private void getAppInfoFromServer() {
        LogUtils.d("getAppInfoFromServer");
        HttpRequest httpRequest = new HttpRequest();
        httpRequest.requestGet(Config.VERSION_URL, new RequestCallback() {
            @Override
            public void onSuccess(String content) {
                Gson gson = new Gson();
                //将Json字符串解析为AppInfo对象
                AppInfo remoteAppInfo = gson.fromJson(content,AppInfo.class);
                LogUtils.d("服务器版本信息--->"+remoteAppInfo);

                if(remoteAppInfo.getVersionCode()>mLocalAppInfo.getVersionCode()){
                    LogUtils.d("有更新，弹出升级对话框");
                    showUpdateDialog();
                }else {
                    LogUtils.d("无更新，进入主界面");
                    startHomeActivity();
                }
            }

            @Override
            public void onFail(String errorMsg) {
                Toast.makeText(SplashActivity.this,errorMsg,Toast.LENGTH_SHORT).show();
                LogUtils.e("获取版本信息异常--->"+errorMsg);
                startHomeActivity();
            }
        });
    }

    /**
     * 进入主界面
     */
    private void startHomeActivity() {
        MainActivity.start(SplashActivity.this);
        finish();
    }


    /**
     * 显示升级对话框
     */
    private void showUpdateDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.app_update);//设置标题：发现新版本
        builder.setMessage(mRemoteAppInfo.getDescription());//设置内容
        builder.setPositiveButton("立即更新", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                //开始下载apk
                downloadApk(mRemoteAppInfo.getDownloadUrl());
            }
        });
        builder.setNegativeButton("以后再说", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                startHomeActivity();
            }
        });

        //点击返回键的监听
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                startHomeActivity();
            }
        });
        builder.show();
    }


    /**
     * 下载APK
     *
     * @param downloadUrl apk文件的网络路径
     */
    private void downloadApk(String downloadUrl) {
        if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            Toast.makeText(this, "没有找到sdcard", Toast.LENGTH_SHORT).show();
            return;
        }
        //显示下载进度
        //mTvProgress.setVisibility(View.VISIBLE);

//        HttpUtils httpUtils = new HttpUtils();
//
//        //获取sdcard根目录
//        String path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/mobileSafe.apk";
//        httpUtils.download(downloadUrl, path, new RequestCallBack<File>() {
//            //下载成功
//            @Override
//            public void onSuccess(ResponseInfo<File> responseInfo) {
//                LogUtils.d( "下载成功--->" + responseInfo.result.getAbsolutePath());
//                installApk(responseInfo.result.getAbsolutePath());
//            }
//
//            //下载失败
//            @Override
//            public void onFailure(HttpException e, String s) {
//                Toast.makeText(SplashActivity.this, "下载失败", Toast.LENGTH_SHORT).show();
//                Log.i(TAG_LOG, "下载失败--->" + s);
//                startMainActivity();
//            }
//
//            @Override
//            public void onLoading(long total, long current, boolean isUploading) {
//                super.onLoading(total, current, isUploading);
//                Log.i(TAG_LOG, "total--->" + total + ",current--->" + current);
//                int percent = (int) (current * 100 / total);
//                mTvProgress.setText("下载进度：" + percent + "%");
//            }
//        });
    }

    /**
     * 拷贝数据库
     * @param dbName 数据库文件名
     */
    private void copyDb(String dbName) {
        AssetManager assets = getAssets();
        File filesDir = getFilesDir();
        File desFile = new File(filesDir, dbName);

        if(desFile.exists()){
            showLog("copyDb()","数据库已存在");
            return;
        }
        InputStream in = null;
        FileOutputStream out = null;
        try {
            //in=context.getClass().getClassLoader().getResourceAsStream("assets/"+names[i]);
            in = assets.open(dbName);
            out = new FileOutputStream(desFile);
            int len = 0;
            byte[] buffer = new byte[1024];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
                out.flush();
            }
        } catch (IOException e) {
            showLog("copyDb error",e.getMessage());
        } finally {
            try {
                in.close();
                out.close();
            } catch (IOException e) {
                showLog("copyDb io error",e.getMessage());
            }
        }
    }

}
